package com.jdkreader.concurrency;

import java.util.concurrent.TimeUnit;

/**
 * 生产者消费者问题 厨师类
 */
public class Chef implements Runnable{

    private Restaurant restaurant;

    //烹饪的食物数量
    private int count = 0;

    public Chef(Restaurant restaurant) {
        this.restaurant = restaurant;
    }

    @Override
    public void run() {

        try {
            while (!Thread.interrupted()) {
                synchronized (this) {
                    while (restaurant.meal != null)
                        wait();// 等待meal被拿走
                }
                if (++count == 10) {
                    System.out.println("Out of food,closing");
                    restaurant.exec.shutdownNow();//向每个线程发送Interrupt
                    return;//如果没有直接return 将多执行了下面的 Order up ,所以一般情况下都要直接return
                }

                System.out.println("Order up! ");
                synchronized (restaurant.waitPerson) {
                    // 对notifyAll()的调用必须先获得waitPerson的锁
                    restaurant.meal = new Meal(count);
                    restaurant.waitPerson.notifyAll();
                }
                TimeUnit.MILLISECONDS.sleep(500);//休眠一下是为了给shutdownNow留出时间
            }
        } catch (InterruptedException e) {
            System.out.println("Chef interrupted");
        }
    }
}
